package com.ccx.library.module.user.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.additional.query.impl.QueryChainWrapper;
import com.ccx.library.function.upload.UploadService;
import com.ccx.library.module.role.entity.Role;
import com.ccx.library.module.user.entity.User;
import com.ccx.library.module.user.service.UserService;
import com.ccx.library.response.R;
import com.ccx.library.util.Md5Util;
import com.ccx.library.util.ModelVoIdUtil;
import com.ccx.library.util.WrapperUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.util.List;

@RestController
@RequestMapping("/core")
public class UserController {

    @Resource
    private UserService userService;

    @PostMapping("/register")
    public R Register(@RequestBody User user) {
        user.setPassword(Md5Util.Encryption(user.getPassword()));
        return R.SUCCESS(userService.save(user));
    }

    @GetMapping("/query")
    public R Query(User user) {
        return R.SUCCESS(userService.getOne(WrapperUtil.Query(user)));
    }

    @GetMapping
    public R list() {
        return R.SUCCESS(userService.list(WrapperUtil.orderDesc(User.class)));
    }

    @PutMapping
    public R edit(@RequestBody User user) {
        return R.SUCCESS(userService.update(WrapperUtil.Update(user, ModelVoIdUtil.getId(user), user.getUserId())));
    }

    @DeleteMapping
    public R DeleteBatch(@RequestBody List<String> ids) {
        return R.SUCCESS(userService.removeByIds(ids));
    }

    @GetMapping("/search")
    public R search(User user) {
        return R.SUCCESS(userService.list(WrapperUtil.Search(user)));
    }

    @Value("${local.ipAddr}")
    private String httpUrl;

    @PostMapping("/upload/{id}")
    public R upload(MultipartFile file, @PathVariable("id") String userId) {
        return R.SUCCESS(UploadService.Upload(0, file, (data) -> {
            User user = new User();
            user.setUserId(userId);
            user.setImg(httpUrl + data.getFileName());
            userService.update(WrapperUtil.Update(user, ModelVoIdUtil.getId(user), user.getUserId()));
        }));
    }
}
